package redis.client;

import com.lx.idgenerator.exception.RedisOperationFailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lX
 * @version JDK 8
 * @className RedisClientManager (此处以class为例)
 * @date 2024/11/9
 * @description TODO
 */
public class RedisClientManager  {

    Logger logger = LoggerFactory.getLogger(RedisClient.class);

    private final RedisClient master;
    private final RedisClient back;


    private final Lock lock = new ReentrantLock();




    public RedisClientManager(RedisClient master, RedisClient slave) {
        this.master = master;
        this.back = slave;
    }

    /**
     * 一个实例只有一个线程会触发扩容，所以这里不用加锁
     * @param key
     * @param step
     * @return
     */
    public Long getNextId(String key,long step) {
        Long currentId;
        Long backCurrentId;
        lock.lock();
        try {
            currentId = master.incrAndGetPrevious(key,step);
            backCurrentId = back.incrAndGetPrevious(key,step);
            while (backCurrentId < currentId) {
                backCurrentId = back.incrAndGetPrevious(key,step);
            }
            while (currentId < backCurrentId) {
                currentId = master.incrAndGetPrevious(key,step);
            }

        } catch (Exception e) {
            logger.error("Redis操作失败, key: {}, step: {}, 失败原因: {}", key, step, e.getMessage());            throw new RedisOperationFailException();
        }finally {
            lock.unlock();
        }
        return currentId;
    }


}
